import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置 NProgress
NProgress.configure({ showSpinner: false })

// 路由配置 - 仅包含已存在的页面
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@views/Dashboard/index.vue'),
    meta: {
      title: '仪表板',
      icon: 'Odometer'
    }
  },
  {
    path: '/devices',
    name: 'Devices',
    component: () => import('@views/Devices/index.vue'),
    meta: {
      title: '设备管理',
      icon: 'Monitor'
    }
  },
  {
    path: '/accounts',
    name: 'Accounts',
    component: () => import('@views/Accounts/index.vue'),
    meta: {
      title: '账号管理',
      icon: 'Avatar'
    }
  },
  {
    path: '/tasks',
    name: 'Tasks',
    component: () => import('@views/Tasks/index.vue'),
    meta: {
      title: '任务管理',
      icon: 'List'
    }
  },
  {
    path: '/device-control-demo',
    name: 'DeviceControlDemo',
    component: () => import('@views/DeviceControlDemo.vue'),
    meta: {
      title: '设备控制演示',
      icon: 'Connection'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    return { top: 0 }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - SocialMatrix Pro`
  } else {
    document.title = 'SocialMatrix Pro'
  }
  
  next()
})

router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})

router.onError((error) => {
  console.error('Router error:', error)
  NProgress.done()
})

export default router